package net.sourceforge.peertwitter.core.applications.communication;

import java.util.HashSet;
import java.util.Set;

import net.sourceforge.peertwitter.chain.EventChainImpl;
import net.sourceforge.peertwitter.core.applications.communication.messaging.ReliableMessage;
import net.sourceforge.peertwitter.core.events.MessageDelivery;
import net.sourceforge.peertwitter.core.events.Event;
import net.sourceforge.peertwitter.scamp.messaging.JoinMessage;
import net.sourceforge.peertwitter.scamp.messaging.JoinMessageAck;
import rice.environment.Environment;
import rice.p2p.commonapi.Endpoint;
import rice.p2p.commonapi.Id;
import rice.p2p.commonapi.Message;

public class ScampImpl extends EventChainImpl<Event> implements MBGroupCommunication {

	private final Endpoint endpoint;
	private final Environment env;
	private final Set<Id> swarms;
	private final SwarmFactory factory;
	private final SwarmContainer swarmContainer;

	public ScampImpl(Environment env, Endpoint endpoint, SwarmFactory factory, SwarmContainer swarmContainer) {
		this.env = env;
		this.endpoint = endpoint;
		this.factory = factory;
		this.swarmContainer = swarmContainer;
		this.swarms = new HashSet<Id>(1);
	}
	

	@Override
	public void join(Id group) {
		if (endpoint.getId().equals(group)) {
			swarmContainer.addSwarm(factory.createSwarm(false));
		} else {
			endpoint.route(group, new JoinMessage(endpoint.getLocalNodeHandle(), group, env.getTimeSource().currentTimeMillis()), null);
		}
	}

	@Override
	public void leave(Id group) {
	}

	@Override
	public void sendReliable(Id group, ReliableMessage message) {
	}

	@Override
	public void send(Message message) {

	}


	@Override
	public void deliver(Event event) {
		if (event instanceof MessageDelivery) {
			MessageDelivery msg = (MessageDelivery)event;
			if (msg.getMessage() instanceof JoinMessage) {
				JoinMessage jm = (JoinMessage)msg.getMessage();
				if (endpoint.getId().equals(jm.getGroup())) {
					if (swarmContainer.exists(endpoint.getId())) {
						swarmContainer.get(endpoint.getId()).enable();
					} else {
						swarmContainer.addSwarm(factory.createSwarm(true));
					}
					endpoint.route(null, new JoinMessageAck(jm, this.endpoint.getLocalNodeHandle()), jm.getSender());
				}
			}
		}
		super.deliver(event);
	}

	
}
